package com.czk.doc;

import com.czk.util.ClientUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * 模糊查询
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/14 17:52
 */
public class FuzzyQuery {
    public static void main(String[] args) throws Exception {
        // 客户端
        RestHighLevelClient highLevelClient = ClientUtil.getHighLevelClient();
        // 构建请求
        SearchRequest searchRequest = new SearchRequest();
        // builder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 模糊查询
        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("title", "java");
        // 设置
        searchSourceBuilder.query(fuzzyQueryBuilder);
        // 设置过滤字段
        String[] exclude = {};
        String[] include = {"title"};
        searchSourceBuilder.fetchSource(include, exclude);
        //
        searchRequest.indices("jd_goods").source(searchSourceBuilder);
        // 响应
        SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit.getSourceAsString());
        }
        highLevelClient.close();
    }
}
